const express = require('express');
const router = express.Router();
const { query } = require('../database/db');

const checkPermission = require('../middleware/checkPermission');
const auth = require('../middleware/auth');

// 教师获取考试列表
router.get('/exams', auth, async (req, res) => {
    try {
        const { class_id, status, page_size = 10, page = 1 } = req.query;

        // 检查用户角色
        const user = await query('SELECT role_id FROM users WHERE id = ?', [req.user.id]);
        const isSuperAdmin = [3, 6].includes(user[0].role_id); // SuperAdmin和SuperAdmin2
        const isTeacherAdmin = user[0].role_id === 2; // TeacherAdmin

        let sql = `
            SELECT 
                e.id,
                e.name,
                e.type,
                e.date,
                e.total_score,
                e.average_score,
                e.student_count,
                c.name AS class_name,
                COUNT(se.id) AS assigned_students,
                u.truename AS teacher_name
            FROM exams e
            JOIN classes c ON e.class_id = c.id
            LEFT JOIN student_exams se ON e.id = se.exam_id
            LEFT JOIN users u ON u.class_id = c.id AND u.role_id IN (2,7) AND u.state = 0
        `;

        let countSql = `SELECT COUNT(DISTINCT e.id) as total FROM exams e JOIN classes c ON e.class_id = c.id`;
        let conditions = [];
        let params = [];

        // 如果不是超级管理员或教师管理员，则只能查看自己班级的考试
        if (!isSuperAdmin && !isTeacherAdmin) {
            // 获取当前教师负责的班级ID
            const teacherClasses = await query(
                'SELECT class_id FROM users WHERE id = ? AND role_id IN (2,7) AND state = 0',
                [req.user.id]
            );

            if (teacherClasses.length === 0) {
                return res.json({
                    code: 200,
                    data: {
                        list: [],
                        total: 0,
                        page: parseInt(page),
                        page_size: parseInt(page_size)
                    }
                });
            }

            const classIds = teacherClasses.map(c => c.class_id);
            conditions.push(`e.class_id IN (?)`);
            params.push(classIds);
        }

        // 添加筛选条件
        if (class_id) {
            conditions.push(`e.class_id = ?`);
            params.push(class_id);
        }
        if (status !== undefined) {
            conditions.push(`e.state_del = ?`);
            params.push(status);
        }

        // 添加WHERE子句
        if (conditions.length > 0) {
            const whereClause = ` WHERE ${conditions.join(' AND ')}`;
            sql += whereClause;
            countSql += whereClause;
        }

        // 添加GROUP BY和分页
        sql += ` GROUP BY e.id, c.name, u.truename 
                ORDER BY e.date DESC 
                LIMIT ? OFFSET ?`;
        params.push(parseInt(page_size), (parseInt(page) - 1) * parseInt(page_size));

        // 执行查询
        const [exams, totalResult] = await Promise.all([
            query(sql, params),
            query(countSql, params.slice(0, -2))
        ]);

        res.json({
            code: 200,
            data: {
                list: exams,
                total: totalResult[0].total,
                page: parseInt(page),
                page_size: parseInt(page_size)
            }
        });
    } catch (error) {
        console.error('获取考试列表失败:', error);
        res.status(500).json({ code: 500, msg: '获取考试列表失败' });
    }
});

// 教师获取考试详情
router.get('/exams/:id', auth, async (req, res) => {
    const { id } = req.params;

    try {
        // 获取考试基本信息
        const [exam] = await query(`
            SELECT e.*, c.name AS class_name 
            FROM exams e
            JOIN classes c ON e.class_id = c.id
            WHERE e.id = ?
        `, [id]);

        if (!exam) {
            return res.status(404).json({ code: -1, msg: '考试不存在' });
        }

        // 获取考试题目
        const questions = await query(
            'SELECT * FROM exam_questions WHERE exam_id = ? ORDER BY question_order',
            [id]
        );

        // 获取学生考试状态
        const students = await query(`
            SELECT 
                se.id,
                se.student_id,
                s.name AS student_name,
                se.status,
                se.total_score,
                se.submit_time
            FROM student_exams se
            JOIN students s ON se.student_id = s.id
            WHERE se.exam_id = ?
        `, [id]);

        res.json({
            code: 200,
            data: {
                ...exam,
                questions,
                students
            }
        });
    } catch (error) {
        console.error('获取考试详情失败:', error);
        res.status(500).json({ code: 500, msg: '获取考试详情失败' });
    }
});

// 教师批量添加考试题目
router.post('/exams/:id/questions/batch', auth, async (req, res) => {
    const { id: exam_id } = req.params;
    const { questions } = req.body; // questions是一个题目数组

    // 验证参数
    if (!Array.isArray(questions) || questions.length === 0) {
        return res.status(400).json({ code: 400, msg: '请提供有效的题目数组' });
    }

    // 验证每个题目的必填字段
    for (const question of questions) {
        if (!question.question_type || !question.question_text ||
            !question.question_order || !question.score) {
            return res.status(400).json({
                code: 400,
                msg: '题目缺少必要参数: question_type, question_text, question_order 或 score'
            });
        }
    }

    try {
        // 检查考试是否存在
        const exam = await query('SELECT id FROM exams WHERE id = ?', [exam_id]);
        if (!exam) {
            return res.status(404).json({ code: 404, msg: '考试不存在' });
        }

        // 检查是否有学生已提交考试
        const submitted = await query(
            'SELECT COUNT(*) as count FROM student_exams WHERE exam_id = ? AND status = 3',
            [exam_id]
        );

        if (submitted[0].count > 0) {
            return res.status(400).json({
                code: 400,
                msg: '已有学生提交考试，无法添加题目'
            });
        }

        // 批量插入题目
        const values = questions.map(q => [
            exam_id,
            q.question_type,
            q.question_text,
            q.question_order,
            q.score,
            q.options ? JSON.stringify(q.options) : null,
            q.correct_answer
        ]);

        const result = await query(
            `INSERT INTO exam_questions 
             (exam_id, question_type, question_text, question_order, score, options, correct_answer) 
             VALUES ?`,
            [values]
        );

        // 更新考试总分
        const total = await query(
            'SELECT SUM(score) as total FROM exam_questions WHERE exam_id = ?',
            [exam_id]
        );
        await query(
            'UPDATE exams SET total_score = ? WHERE id = ?',
            [total[0].total || 0, exam_id]
        );

        res.json({
            code: 200,
            msg: '批量添加题目成功',
            data: { affectedRows: result.affectedRows }
        });
    } catch (error) {
        console.error('批量添加题目失败:', error);
        res.status(500).json({ code: 500, msg: '批量添加题目失败' });
    }
});

// 教师批量修改考试题目
router.put('/exams/:id/questions/batch', auth, async (req, res) => {
    const { id: exam_id } = req.params;
    const { questions } = req.body; // questions是一个题目数组，包含question_id

    // 验证参数
    if (!Array.isArray(questions) || questions.length === 0) {
        return res.status(400).json({ code: 400, msg: '请提供有效的题目数组' });
    }

    // 验证每个题目的必填字段
    for (const question of questions) {
        if (!question.question_id || !question.question_type ||
            !question.question_text || !question.question_order ||
            !question.score) {
            return res.status(400).json({
                code: 400,
                msg: '题目缺少必要参数: question_id, question_type, question_text, question_order 或 score'
            });
        }
    }

    try {
        // 检查考试是否存在
        const [exam] = await query('SELECT id FROM exams WHERE id = ?', [exam_id]);
        if (!exam) {
            return res.status(404).json({ code: 404, msg: '考试不存在' });
        }

        // 检查是否有学生已提交考试
        const [submitted] = await query(
            'SELECT COUNT(*) as count FROM student_exams WHERE exam_id = ? AND status = 3',
            [exam_id]
        );

        if (submitted[0].count > 0) {
            return res.status(400).json({
                code: 400,
                msg: '已有学生提交考试，无法修改题目'
            });
        }

        // 检查所有题目是否属于该考试
        const questionIds = questions.map(q => q.question_id);
        const [existingQuestions] = await query(
            'SELECT question_id FROM exam_questions WHERE exam_id = ? AND question_id IN (?)',
            [exam_id, questionIds]
        );

        if (existingQuestions.length !== questionIds.length) {
            return res.status(400).json({
                code: 400,
                msg: '部分题目不属于该考试或不存在'
            });
        }

        // 使用事务处理批量更新
        const connection = await pool.getConnection;
        await connection.beginTransaction;

        try {
            // 批量更新题目
            for (const question of questions) {
                await connection.query(
                    `UPDATE exam_questions SET 
                        question_type = ?,
                        question_text = ?,
                        question_order = ?,
                        score = ?,
                        options = ?,
                        correct_answer = ?
                     WHERE question_id = ?`,
                    [
                        question.question_type,
                        question.question_text,
                        question.question_order,
                        question.score,
                        question.options ? JSON.stringify(question.options) : null,
                        question.correct_answer,
                        question.question_id
                    ]
                );
            }

            // 更新考试总分
            const [total] = await connection.query(
                'SELECT SUM(score) as total FROM exam_questions WHERE exam_id = ?',
                [exam_id]
            );
            await connection.query(
                'UPDATE exams SET total_score = ? WHERE id = ?',
                [total[0].total || 0, exam_id]
            );

            await connection.commit;

            res.json({
                code: 200,
                msg: '批量修改题目成功',
                data: { updatedCount: questions.length }
            });
        } catch (error) {
            await connection.rollback;
            throw error;
        } finally {
            connection.release;
        }
    } catch (error) {
        console.error('批量修改题目失败:', error);
        res.status(500).json({ code: 500, msg: '批量修改题目失败' });
    }
});

// 教师删除考试题目
router.delete('/questions/:id', auth, async (req, res) => {
    const { id } = req.params;

    try {
        // 检查题目是否存在
        const [question] = await query(
            'SELECT * FROM exam_questions WHERE question_id = ?',
            [id]
        );

        if (!question) {
            return res.status(404).json({ code: 404, msg: '题目不存在' });
        }

        // 检查是否有学生已提交考试
        const [submitted] = await query(
            'SELECT COUNT(*) as count FROM student_exams WHERE exam_id = ? AND status = 3',
            [question[0].exam_id]
        );

        if (submitted[0].count > 0) {
            return res.status(400).json({
                code: 400,
                msg: '已有学生提交考试，无法删除题目'
            });
        }

        // 删除题目
        await query('DELETE FROM exam_questions WHERE question_id = ?', [id]);

        // 更新考试总分
        const [total] = await query(
            'SELECT SUM(score) as total FROM exam_questions WHERE exam_id = ?',
            [question[0].exam_id]
        );
        await query(
            'UPDATE exams SET total_score = ? WHERE id = ?',
            [total[0].total || 0, question[0].exam_id]
        );

        res.json({
            code: 200,
            msg: '删除题目成功'
        });
    } catch (error) {
        console.error('删除题目失败:', error);
        res.status(500).json({ code: 500, msg: '删除题目失败' });
    }
});

// 教师批改学生答案
router.put('/answers/:id/grade', auth, async (req, res) => {
    const { id } = req.params;
    const { score, teacher_comment } = req.body;

    try {
        // 检查答案是否存在
        const [answer] = await query(`
            SELECT sa.*, se.exam_id 
            FROM student_answers sa
            JOIN student_exams se ON sa.student_exam_id = se.id
            WHERE sa.answer_id = ?
        `, [id]);

        if (!answer) {
            return res.status(404).json({ code: 404, msg: '答案不存在' });
        }

        // 更新批改信息
        await query(
            `UPDATE student_answers 
             SET score = ?, teacher_comment = ?, corrected_at = NOW  
             WHERE answer_id = ?`,
            [score, teacher_comment, id]
        );

        // 重新计算总分
        const [total] = await query(`
            SELECT SUM(score) AS total_score 
            FROM student_answers 
            WHERE student_exam_id = ?
        `, [answer.student_exam_id]);

        await query(
            'UPDATE student_exams SET total_score = ? WHERE id = ?',
            [total[0].total_score || 0, answer.student_exam_id]
        );

        // 更新考试平均分
        await query(`
            UPDATE exams e
            SET e.average_score = (
                SELECT AVG(se.total_score)
                FROM student_exams se
                WHERE se.exam_id = ?
            ),
            e.student_count = (
                SELECT COUNT(*)
                FROM student_exams se
                WHERE se.exam_id = ? AND se.status = 3
            )
            WHERE e.id = ?
        `, [answer.exam_id, answer.exam_id, answer.exam_id]);

        res.json({ code: 200, msg: '批改成功' });
    } catch (error) {
        console.error('批改答案失败:', error);
        res.status(500).json({ code: 500, msg: '批改答案失败' });
    }
});

// 教师获取学生考试答案列表
router.get('/exams/:id/answers', auth, async (req, res) => {
    const { id: exam_id } = req.params;
    const { status, page_size = 10, page = 1 } = req.query;

    try {
        let sql = `
            SELECT 
                sa.answer_id,
                sa.answer_text,
                sa.score,
                sa.teacher_comment,
                sa.corrected_at,
                eq.question_text,
                eq.question_type,
                eq.score AS max_score,
                s.id AS student_id,
                s.name AS student_name,
                se.status
            FROM student_answers sa
            JOIN exam_questions eq ON sa.question_id = eq.question_id
            JOIN student_exams se ON sa.student_exam_id = se.id
            JOIN students s ON se.student_id = s.id
            WHERE se.exam_id = ?
        `;

        let countSql = `SELECT COUNT(*) as total FROM student_answers sa JOIN student_exams se ON sa.student_exam_id = se.id WHERE se.exam_id = ?`;
        let conditions = [];
        let params = [exam_id];

        // 添加筛选条件
        if (status) {
            conditions.push(`se.status = ?`);
            params.push(status);
        }

        // 添加WHERE子句
        if (conditions.length > 0) {
            const whereClause = ` AND ${conditions.join(' AND ')}`;
            sql += whereClause;
            countSql += whereClause;
        }

        // 添加分页
        sql += ` ORDER BY s.name ASC, eq.question_order ASC LIMIT ? OFFSET ?`;
        params.push(parseInt(page_size), (parseInt(page) - 1) * parseInt(page_size));

        // 执行查询
        const [answers, totalResult] = await Promise.all([
            query(sql, params),
            query(countSql, params.slice(0, -2))
        ]);

        res.json({
            code: 200,
            data: {
                list: answers,
                total: totalResult[0].total,
                page: parseInt(page),
                page_size: parseInt(page_size)
            }
        });
    } catch (error) {
        console.error('获取学生答案失败:', error);
        res.status(500).json({ code: 500, msg: '获取学生答案失败' });
    }
});

module.exports = router;